package dao.admin.impl;

import dao.BaseDao;
import dao.admin.CardListDao;
import entity.Borrow_books;
import entity.Borrow_card;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * CardListDaoImpl
 *
 * @author lenovo
 * @since 2023/9/4
 */
public class CardListDaoImpl extends BaseDao implements CardListDao {
    @Override
    public List<Borrow_card> getList(String condition, String conditionValue, int pageIndex, int pageSize) {
        String sql = "select * from borrow_card";
        if (condition != null && conditionValue != null && !condition.isEmpty() && !conditionValue.isEmpty()){
            sql += " where " + condition + " like concat('%',?,'%')";
        }
        sql += " order by id desc limit ?,?";
        List<Borrow_card> list = new ArrayList<>();
        Borrow_card books = null;
        Connection conn = getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = conn.prepareStatement(sql);
            int num = 0;
            if (condition != null && conditionValue != null && !condition.isEmpty() && !conditionValue.isEmpty()){
                pstmt.setString(++num,conditionValue);
            }
            pstmt.setInt(++num,pageIndex);
            pstmt.setInt(++num,pageSize);
            rs = pstmt.executeQuery();
            while (rs.next()){
                books = new Borrow_card();
                books.setId(rs.getInt("id"));
                books.setPassword(rs.getString("password"));
                books.setReader(rs.getString("reader"));
                books.setRule_id(rs.getInt("rule_id"));
                books.setStatus(rs.getInt("status"));
                list.add(books);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(rs,pstmt,conn);
        }
        return list;
    }

    @Override
    public int totalCount(String condition, String conditionValue) {
        String sql = "select COUNT(*) c from borrow_card";
        if (condition != null && conditionValue != null && !condition.isEmpty() && !conditionValue.isEmpty()){
            sql +=" where " + condition + " like concat('%',?,'%')";
        }
        int total = 0;
        Connection conn = getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = conn.prepareStatement(sql);
            if (condition != null && conditionValue != null && !condition.isEmpty() && !conditionValue.isEmpty()){
                pstmt.setString(1,conditionValue);
            }
            rs = pstmt.executeQuery();
            if (rs.next()){
                total = rs.getInt("c");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(rs,pstmt,conn);
        }
        return total;
    }
}
